package com.jsmile.cloud.msgcenter.zf.strategy.factory;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.jsmile.cloud.accountcenter.api.enums.PayTypeEnum;
import com.jsmile.cloud.msgcenter.zf.strategy.interfaces.IPay;

import lombok.extern.slf4j.Slf4j;

/**
 * 支付策略
 */
@Service
@Slf4j
public class PayStrategyFactory implements ApplicationContextAware {

    private final Map<PayTypeEnum, IPay> syncHandlerMap = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, IPay> beansOfTypeMap = applicationContext.getBeansOfType(IPay.class);
        if (beansOfTypeMap != null) {
            beansOfTypeMap.forEach((key, strategy) -> syncHandlerMap.putIfAbsent(strategy.payType(), strategy));
        }
    }

    public IPay findStrategy(PayTypeEnum payType) {
        return syncHandlerMap.get(payType);
    }

    public IPay findStrategy(int payType) {
        return syncHandlerMap.get(PayTypeEnum.nameOf(payType));
    }

    public Optional<IPay> findStrategyOptional(PayTypeEnum payType) {
        return Optional.ofNullable(syncHandlerMap.get(payType));
    }
}
